	<template>
	<view class="conteiner diy-template flex-column" :style="homeStyle">
		<qh-navbar :title="storeName" :bgColor="PageData.titleBarData.data.barBackgroundColor" :color="PageData.titleBarData.data.barFontColor?PageData.titleBarData.data.barFontColor:'#000000'">
		</qh-navbar>
		<view class="diy-template-content flex-column-100">
			<view v-for="(item,index) in PageData.compontentData" :key="index">
				<diy-float v-if="item.sign === 'diy-float'" :componentData="item.data" @callback="callback"></diy-float>
				<diy-dialog v-if="item.sign === 'diy-dialog'" :componentData="item.data" @callback="callback"></diy-dialog>
				<block v-if="item.sign === 'diy-bar'">
					<view class="diy-sticky" :style="{
						'top':stickyTopObject['diy-bar-'+index].offSetTop+'px'
					}" v-if="item.data.sticky && scrollTop > stickyTopObject['diy-bar-'+index].scrollTop">
						<diy-bar :componentData="item" @callback="callback"></diy-bar>
					</view>
				</block>
			</view>
			<qh-scroll-view parent-el-name=".diy-template-content" @init="initScroll" scroll-y
				@scroll="onScroll" class="" refresher-enabled
				@refresherrefresh="onPagePullDownRefresh" :refresher-triggered="isRefresh"
				refresher-background="transparent">
				<view :style="getBackGround()+';height:100%'">
					<block v-for="(item,index) in PageData.compontentData" :key="index">
						<diy-img v-if="item.sign === 'diy-img'" :componentData="item" @callback="callback"></diy-img>
						<diy-swiper v-if="item.sign === 'diy-swiper'" :componentData="item" @callback="callback"></diy-swiper>
						<diy-text v-if="item.sign === 'diy-text'" :componentData="item" @callback="callback"></diy-text>
						<diy-btn v-if="item.sign === 'diy-btn'" :componentData="item" @callback="callback"></diy-btn>
						<diy-word v-if="item.sign === 'diy-word'" :componentData="item" @callback="callback"></diy-word>
						<diy-goods @toAddToCar="toAddToCar" @getSku="getSku" v-if="item.sign === 'diy-goods'" :componentData="item" @callback="callback"></diy-goods>
						<diy-video v-if="item.sign === 'diy-video'" :componentData="item" @callback="callback"></diy-video>
						<diy-wrap v-if="item.sign == 'diy-wrap'" :componentData="item.data.componentData" :config="item.data.config" @callback="callback">
						</diy-wrap>
						<diy-doub-wrap v-if="item.sign == 'diy-doub-wrap'" :componentData="item.data.componentData" :config="item.data.config" @callback="callback">
						</diy-doub-wrap>
						<view class="diy-bar-wrap" v-if="item.sign === 'diy-bar'" :id="'diy-bar-'+index" :data-index="index">
							<diy-bar :componentData="item" @callback="callback"></diy-bar>
						</view>
						<diy-notice v-if="item.sign === 'diy-notice'" :componentData="item" @callback="callback"></diy-notice>
						<diy-navigate v-if="item.sign === 'diy-navigate'" :componentData="item" @callback="callback"></diy-navigate>
						<!--营销组件-->
						<diy-coupon :cityCode="cityCode" v-if="item.sign === 'diy-coupon'" :componentData="item" @callback="callback"></diy-coupon>
						<diy-promotion v-if="item.sign === 'diy-promotion'" :componentData="item.data" @callback="callback"
							AllUrl="/pages/product/promotion/promotion" dataUrl="/DiyStore/Api/getPromotionDataTime" icon="icon-cuxiaozhengce"></diy-promotion>
						<diy-promotion v-if="item.sign === 'diy-seckill'" :componentData="item.data" @callback="callback"
							AllUrl="/pages/index/Seckill-purchase/Seckill-purchase" dataUrl="/DiyStore/Api/getSecKillTimesDetail" icon="icon-miaosha">
						</diy-promotion>
						<diy-promotion v-if="item.sign === 'diy-group'" :componentData="item.data" @callback="callback"
							AllUrl="/pages/index/Group-purchase/Group-purchase" dataUrl="/DiyStore/Api/getGroupTimesDetail" icon="icon-ziyuan"></diy-promotion>
						<diy-promotion v-if="item.sign === 'diy-presale'" :componentData="item.data" @callback="callback"
							AllUrl="/pages/index/advanceSale/advanceSale" dataUrl="/DiyStore/Api/getAdvanceTimesDetail" icon="icon-yushou"></diy-promotion>
						<diy-gift-card v-if="item.sign === 'diy-gift_card'" :componentData="item" @callback="callback"></diy-gift-card>
						<diy-address v-if="item.sign === 'diy-address'" :componentData="item" @callback="callback"></diy-address>
					</block>
				</view>
			</qh-scroll-view>
		</view>
		<!-- 选择规格弹窗 -->
		<block v-if="showSelectSku">
			<choose-sku :sku="sku" :goodsinfo="goods" @close="closeSku" zIndex="2147483647"></choose-sku>
		</block>
		<view class="reward_container" v-if='reward'>
			<view class='box'>
				<image :src='rewardBg' class='reward-bg'></image>
				<view @click='toOpen' class="reward-open" :class="{'reward-rotate': rotate}">
					<image v-if='rotate' mode="aspectFit" :src='open1Image'></image>
					<image v-else mode="aspectFit" :src='openImage'></image>
				</view>
				<view class='reward-money' v-if='open'>
					<text>￥</text>
					<text>{{money}}</text>
				</view>
				<view class='reward-tip' v-if='!open'>恭喜发财，大吉大利！</view>
				<view class='reward-tip' v-else>已放入会员卡余额</view>
				<view @click='closeReward' class='reward-close'>
					<icon type='cancel' size='30' color='#ffffff'></icon>
				</view>
			</view>
		</view>
	</view>

</template>
<script>
	var app = getApp().globalData
	import diyBar from "@/pages/store/components/diy-bar/diy-bar"
	import diyImg from "@/pages/store/components/diy-img/diy-img"
	import diySwiper from "@/pages/store/components/diy-swiper/diy-swiper"
	import diyText from "@/pages/store/components/diy-text/diy-text"
	import diyBtn from "@/pages/store/components/diy-btn/diy-btn"
	import diyWord from "@/pages/store/components/diy-word/diy-word"
	import diyGoods from "@/pages/store/components/diy-goods/diy-goods"
	import diyVideo from "@/pages/store/components/diy-video/diy-video"
	import diyWrap from "@/pages/store/components/diy-wrap/diy-wrap"
	import diyDoubWrap from "@/pages/store/components/diy-doub-wrap/diy-doub-wrap"
	import diyNotice from "@/pages/store/components/diy-notice/diy-notice"
	import diyNavigate from "@/pages/store/components/diy-navigate/diy-navigate"
	import diyCoupon from "@/pages/store/components/diy-coupon/diy-coupon"
	import diyFloat from "@/pages/store/components/diy-float/diy-float"
	import diyDialog from "@/pages/store/components/diy-dialog/diy-dialog"
	import diyPromotion from "@/pages/store/components/diy-promotion/diy-promotion"
	import diyGiftCard from "@/pages/store/components/diy-gift_card/diy-gift_card"
	import diyAddress from "@/pages/store/components/diy-address/diy-address"
	import qhScrollMixin from "@/components/qh-scroll-view/mixins.js";

	export default {
		mixins: [qhScrollMixin], // 使用mixin
		components: {
			diyBar,
			diyImg,
			diySwiper,
			diyText,
			diyBtn,
			diyWord,
			diyGoods,
			diyVideo,
			diyWrap,
			diyDoubWrap,
			diyNotice,
			diyNavigate,
			diyCoupon,
			diyFloat,
			diyDialog,
			diyPromotion,
			diyGiftCard,
			diyAddress
		},
		props: [
			"pageContent"
		],
		watch:{
			"PageData.titleBarData.data":{
				immediate:true,
				handler(n){
					if (this.PageDataState == 1 && n.systemIconColor) {
						uni.setNavigationBarColor({
							// #ifdef MP-WEIXIN
							frontColor:n.systemIconColor==1?"#000000":"#ffffff",
							// #endif
							backgroundColor:n.systemIconColor==1?"#ffffff":"#000000"
						});
					}
				}
			}
		},
		data() {
			return {
				isRefresh:false,
				scrollTop:0, // 页面滚动高度
				PageData: {}, // 装修数据
				PageDataState: 0,
				headerHeight: 0, // 头部高度
				diyHeadTop: "", // DIy头部高度
				capsuleHeigth: "",
				navbarHeight: "", // 不知道啥高度
				stickyTopObject: [],
				page_id: "",
				storeList: [], // 门店列表数据
				phone: "", // 手机号
				storeName: "", // 门店名称
				store_id: 0,
				showSelectSku: false,
				sku: {},
				goods: {},
				// 红包数据
				open: false, // 红包没有被打开
				rotate: false,
				reward: false,
				isVip: 0,
				rewardBg: 'https://safood.supplyocta.com/Public/MallSmallApp/reward-bg.png',
				open1Image: 'https://safood.supplyocta.com/Public/MallSmallApp/open-1.png',
				openImage: 'https://www.xzthealth.com/Public/MallSmallApp/open.png',
				money: 0,
				//#ifdef MP-ALIPAY
				cityCode: '', //用户城市编码
				//#endif
			}
		},
		computed: {
			homeStyle() {
				let css = {
					height: `calc(100vh - ${this.$store.bottomHeight + 110}rpx)`,
				};
				return this.$joinStyle(css);
			},
		},
		methods: {
			onShows() {
				// 获取父级页面的值
				this.storeList = this.$root.storeList;
				this.phone = this.$root.phone;
				this.storeName = this.$root.storeName;
				this.cityCode = this.$root.cityCode;
				this.store_id = this.$root.store_id;
				this.page_id = this.$root.page_id;
				this.onPageLoad(this.$root.store_id, this.page_id);
				this.getReward(); // 查找红包
			},
			openDialog(data) {
				const dialogId = data['value'];
				let compontentIndex = -1;
				const flag = this.PageData.compontentData.some((item, index) => {
					if ((item['sign'] === 'diy-dialog') && item['data'] && (item['data']['id'] === dialogId)) {
						compontentIndex = index;
						return true;
					}
				});
				if (flag) {
					// 判断当前是否打开对话框，如果是，表示是从对话框内的点击打开新对话框
					// 获取 层级最高的对应层级
					let dialogZindex = 1960;
					this.PageData.compontentData.forEach((item, index) => {
						if (item['sign'] === 'diy-dialog') {
							if (item['data']['realVisible'] === 1) {
								// 当前是打开的
								if (item['data']['setDialogZindex'] > dialogZindex) {
									dialogZindex = item['data']['setDialogZindex']
								}
								if (item['data']['dialogZindex'] > dialogZindex) {
									dialogZindex = item['data']['dialogZindex']
								}
							}
						}
					});
					dialogZindex += 1;
					this.setData({
						['PageData.compontentData[' + compontentIndex + '].data.realVisible']: 1,
						['PageData.compontentData[' + compontentIndex + '].data.setDialogZindex']: dialogZindex,
					})
				}
			},

			//查找红包
			async getReward() {
				this.open = false; // 红包没有被打开
				this.rotate = false;
				const user = uni.getStorageSync('userInfo');
				const res = await this.$request('SmallProgramApi/Reward/getHomeReward', {
					vid: user.vid ? user.vid : 0,
					store_id: this.store_id,
				});
				if (res.status == 1) {
					this.reward = true;
					this.isVip = user.vid ? 1 : 0; // 是否激活会员卡
				}
			},
			//拆红包
			async toOpen() {
				if (!this.rotate) {
					if (this.isVip != 1) {
						uni.showModal({
							title: '温馨提示',
							content: '您没有激活会员卡，去激活会员领取红包吧！',
							showCancel: true,
							cancelText: '狠心放弃',
							confirmColor: '#ff5c6d',
							confirmText: '去激活',
							success: (re) => {
								if (re.confirm) {
									uni.navigateTo({
										url: '/pages/mine/card/card'
									})
								}
							}
						})
						return;
					}
					this.rotate = true;
					const res = await this.$request('SmallProgramApi/Reward/openHomeReward');

					if (res.status == 1) {
						this.money = res.money;
						this.open = true;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1500
						})
						this.closeReward();
					}
				}
			},
			//关闭拆红包
			closeReward() {
				this.reward = false;
			},
			// 关闭弹窗
			closeDialog(data) {
				const dialogId = data['value'];
				let compontentIndex = -1;
				const flag = this.PageData.compontentData.some((item, index) => {
					if ((item['sign'] === 'diy-dialog') && item['data'] && (item['data']['id'] === dialogId)) {
						compontentIndex = index;
						return true;
					}
				});
				if (flag) {
					this.setData({
						['PageData.compontentData[' + compontentIndex + '].data.realVisible']: 2,
						['PageData.compontentData[' + compontentIndex + '].data.setDialogZindex']: 0,
					});
					// 同时记录标识已经关闭，再次载入不可打开
					this.$store.closeDialogList.push(dialogId);
					
				}
			},
			getBackGround() {
				if (this.PageDataState == 1) {
					if (this.PageData.titleBarData.data.backgroundType == "color") {
						return "background-color:" + this.PageData.titleBarData.data.pageBackgroundColor;
					} else {
						return "background-size:100%;background-repeat:no-repeat;background-position:0px 0px;background-image:url(" + this.PageData.titleBarData
							.data.backgroundImg + ")";
					}
				}
			},
			// 监听滚动事件
			onScroll(event) {
				this.scrollTop = event.detail.scrollTop;
			},
			// 页面重新获取数据的啦
			onPagePullDownRefresh() {
				this.isRefresh = true;
				this.getPageData(this.store_id, this.page_id);
			},
			callback(e) {
				const detail = e.detail;
				if (typeof this[detail.method] === 'function') {
					this[detail.method](detail.data);
				}
			},
			onPageLoad(store_id, page_id) {
				this.navbarHeight = this.$store.statusBarHeight+44;
				this.PageData = this.optimizePageData(this.$root.page_content,this.$store.closeDialogList);
				this.PageDataState = 1;
				this.$nextTick(() => {
					this.stickyTop();
				})
			},
			optimizePageData(data, closeDialogList) {
			  const {compontentData, ...otherData} = JSON.parse(data);
			  const newCompontentData = compontentData.map(res => {
			    if (res.sign === "diy-dialog" && res.data["realVisible"] == 1) {
			      var index = closeDialogList.indexOf(res.data.id);
			      if (index >= 0) {
			        res = Object.assign({}, res, {data: {realVisible: 2}});
			      }
			    }
			    return res;
			  });
			  return {...otherData, compontentData: newCompontentData};
			},
			// 获取装修的DIY数据
			async getPageData(store_id, page_id) {
				let diy_data, url;
				diy_data = {
					store_id: store_id
				}
				if (page_id) {
					diy_data.page_id = page_id;
				}
				url = '/DiyStore/Api/getPageData';
				try {
					const {
						status,
						data,
						message,
					} = await this.$request(url, diy_data);
						if (status == 1) {
							this.PageData = this.optimizePageData(data.content,this.$store.closeDialogList);
							this.PageDataState = 1;
							this.$nextTick(() => {
								this.stickyTop();
							})
						}
						if (this.isRefresh) {
							this.isRefresh = false;
							uni.showToast({
								title: '刷新成功',
								duration: 800,
							});
						}
				} catch (err) {
					if (this.isRefresh) {
						this.isRefresh = false;
						uni.showToast({
							title: '刷新成功',
							duration: 800,
						});
					}
				}
			},
			stickyTop() {
				let that = this;
				const Arr = [];
				[...this.PageData.compontentData].forEach((item, index) => {
					if (item.sign === 'diy-bar' && item.data.sticky) {
						Arr.push(this.getRect('#diy-bar-' + index));
					}
				});
				Promise.all(Arr).then((resArr) => {
					const stickyTopObject = {};
					let offSetTop = 0;
					let lastHeight = 0;
					resArr.forEach((item, index) => {
						if (item === null) {
							offSetTop = -1
						} else {
							if (offSetTop) {
								offSetTop = offSetTop;
							} else {
								offSetTop = that.navbarHeight;
							}
							const totalHeight = item.height;
							offSetTop = offSetTop ? offSetTop : that.data.topBarHeight;
							item.offSetTop = offSetTop;
							stickyTopObject[item.id] = item;
							item.scrollTop = item.top - totalHeight - lastHeight;
							offSetTop += totalHeight;
							lastHeight = totalHeight;
							// 吸顶时  scrollTop 
						}
					});

					if (offSetTop >= 0) {
						that.stickyTopObject = stickyTopObject;

					} else {
						that.errorNum = that.errorNum ? that.errorNum : 0;
						that.errorNum++;
						return Promise.reject();
					}
				}).catch(() => {
					if (that.errorNum && that.errorNum > 10) {} else {
						that.$nextTick(() => {
							that.stickyTop();
						})
					}
				})
			},
			//添加到购物车
			async toAddToCar(data) {
				data.fixed_num = this.sku.canChangeCarNum == 1 ? 0 : 1; //是否不可修改数量
				data.type = 1;
				data.goods_type = 2;
				const res = await this.$mutations.setShoppingCar(data);
				
				if (res) {
					this.sku.canChangeCarNum = 1;
					this.sku.canChangeAddNum = true;
					this.showSelectSku = false;
				}
			},
			//取消选择规格
			closeSku() {
				this.showSelectSku = false;
			},
			//获取SKU
			async getSku(goods) {
				if (goods.attribute_state == 2) {
					this.goods = goods;
					this.showSelectSku = true;
				} else {
					const res = await this.$mutations.setShoppingCar({
						goods_id: goods.goods_id,
						num: 1,
						goods_type: 2,
					});
					if (res) {
						this.showSelectSku = false;
					}
				}
			},

			getRect(selector) {
				return new Promise(resolve => {
					uni.createSelectorQuery().in(this).select(selector).boundingClientRect(rect => {
						// console.log(rect);
						resolve(rect);
					}).exec();
				});
			}
		}
	}
</script>
<style lang="scss">
	.diy-template {
		width: 100%;
		height: 100%;
		background-color: #f6f6f6;

		.diy-template-content {
			overflow-y: scroll;
		}
	}

	.page-static {
		text-align: center;
		color: #999999;
		line-height: 120rpx;
		padding-bottom: 40rpx;
		font-size: 24rpx;
	}

	.s {
		text-decoration: line-through
	}

	.buying {
		// pos
		width: 50%;
		padding: 25rpx 0;
		position: relative;
		left: 20rpx;

		i {
			font-style: normal;
			display: inline-block;
		}

		i:nth-child(1) {
			color: #333333;
			font-size: 32rpx;
			margin-bottom: 8rpx;
			font-weight: bold;
		}

		i:nth-child(2) {
			position: absolute;
			left: 36rpx;
			bottom: 23rpx;
			width: 60rpx;
			height: 6rpx;
			background-color: #FF6433;
			border-radius: 20px;
		}
	}

	.pagesss {
		width: 100%;
		height: 20vh;
		background-color: pink;
	}

	.diy-head {
		position: fixed;
		top: 0;
		width: 100%;
		background-color: #fff;

		.diy-local {
			position: fixed;
			top: 2vh;
		}
	}

	.diy-head {
		position: fixed;
		top: 0;
		width: 100%;
		background-color: #fff;

		.diy-local {
			position: fixed;
			top: 2vh;
		}
	}

	.diy-sticky {
		position: fixed;
		width: 100%;
		left: 0;
		z-index: 2001;
	}

	.draggable-box {
		min-height: 1000px;
	}

	.reward_container {
		width: 100vw;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 2001;

		.box {
			/* #ifdef H5 */
			width: 335px;
			height: 384px;
			/* #endif */
			/* #ifndef H5 */
			width: 670rpx;
			height: 768rpx;
			/* #endif */
			position: relative;
			margin: 0 auto 70px;
			background-color: transparent;
		}
	}

	.reward-bg {
		width: 100%;
		height: 100%;
		border-radius: 2vw;
		position: absolute;
		top: 0;
		left: 0;
	}

	.reward-open {
		/* #ifdef H5 */
		width: 100px;
		height: 100px;
		top: 102px;
		left: 118px;
		/* #endif */
		/* #ifndef H5 */
		width: 200rpx;
		height: 200rpx;
		top: 204rpx;
		left: 236rpx;
		/* #endif */
		border-radius: 50%;
		position: absolute;
		transition: 1.5s;
		font-size: 0;
	}

	.reward-open>image {
		width: 100%;
		height: 100%;
	}

	.reward-rotate {
		transform: rotateY(360deg);
	}

	.reward-title {
		/* #ifdef H5 */
		font-size: 14px;
		/* #endif */
		/* #ifndef H5 */
		font-size: 28rpx;
		/* #endif */
		text-align: center;
		position: relative;
		margin-top: 6vw;
	}

	.reward-money {
		position: absolute;
		/* #ifdef H5 */
		bottom: 105rpx;
		/* #endif */
		/* #ifndef H5 */
		bottom: 210rpx;
		/* #endif */
		left: 0;
		width: 100%;
		text-align: center;
		color: #fdcf9e;
	}

	/* #ifdef H5 */
	.reward-money>text:nth-child(1) {
		font-size: 16px;
	}

	.reward-money>text:nth-child(2) {
		font-size: 34px;
	}

	.reward-tip {
		text-align: center;
		position: absolute;
		bottom: 59px;
		left: 0;
		width: 100%;
		color: #fdcf9e;
		font-size: 16px;
	}

	/* #endif */
	/* #ifndef H5 */
	.reward-money>text:nth-child(1) {
		font-size: 32rpx;
	}

	.reward-money>text:nth-child(2) {
		font-size: 68rpx;
	}

	.reward-tip {
		text-align: center;
		position: absolute;
		bottom: 118rpx;
		left: 0;
		width: 100%;
		color: #fdcf9e;
		font-size: 32rpx;
	}

	/* #endif */

	.reward-close {
		width: 100%;
		position: absolute;
		left: 0;
		bottom: -15vw;
		display: flex;
		justify-content: center;
	}
</style>
